﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace eCompany.Forms
{
    public partial class api_add_company : Form
    {
        private eObj.organisation m_org = null;
        private eObj.company m_company = null;
        private Thread m_LoadCompanyThread = null;
        private delegate void stopLoadHandler(eObj.company c);
        private stopLoadHandler stopLoadDelegate;
        private delegate void updateScreenHandler(string action);
        private updateScreenHandler updateScreenDelegate;

        public api_add_company(ref eObj.organisation org)
        {
            InitializeComponent();
            this.Icon = pics.eCompanyIcon;
            stopLoadDelegate = new stopLoadHandler(stopLoadCompany);
            updateScreenDelegate = new updateScreenHandler(updateScreen);
            m_org = org;
        }

        private void api_add_company_Load(object sender, EventArgs e)
        {
            this.Height = 72;
        }

        private void companyIdTxt_TextChanged(object sender, EventArgs e)
        {
            if (companyIdTxt.Text != "")
                loadCmd.Enabled = true;
            else
                loadCmd.Enabled = false;
        }

        private void loadCmd_Click(object sender, EventArgs e)
        {
            this.Height = 72;
            loadCmd.Enabled = false;
            this.Cursor = Cursors.WaitCursor;
            companyIdTxt.Enabled = false;
            
            loadCompanyFromApi(companyIdTxt.Text);
        }

        public void updateScreen(string action)
        {
            if (action != "")
                loadCmd.Text = action;
            else
                loadCmd.Text = "Load from eRepublik";

            loadCmd.Refresh();
        }

        public void updateScreenThreadSafe(string action)
        {
            this.Invoke(this.updateScreenDelegate,new Object[] {action});
        }

        private void loadCompanyFromApi(string companyId)
        {
            m_LoadCompanyThread = new Thread(loadCompanyProc);
            m_LoadCompanyThread.Start(companyId);
        }

        public void validateCustomControls()
        {
            bool valid = true;
            foreach (Control obj in accountTableLayoutPanel.Controls)
            {
                eCompany.Custom_Controls.small_account_ctrl ctrl = (eCompany.Custom_Controls.small_account_ctrl)obj;
                if (double.IsNaN(ctrl.getValue())) valid = false;
            }
            foreach (Control obj in employeeTableLayoutPanel.Controls)
            {
                eCompany.Custom_Controls.small_employee_ctrl ctrl = (eCompany.Custom_Controls.small_employee_ctrl)obj;
                if (double.IsNaN(ctrl.getValue())) valid = false;
            }
            foreach (Control obj in rawTableLayoutPanelExtended.Controls)
            {
                eCompany.Custom_Controls.small_raw_ctrl ctrl = (eCompany.Custom_Controls.small_raw_ctrl)obj;
                if (double.IsNaN(ctrl.getValue())) valid = false;
            }
            foreach (Control obj in shopsTableLayoutPanelExtended.Controls)
            {
                eCompany.Custom_Controls.small_shop_ctrl ctrl = (eCompany.Custom_Controls.small_shop_ctrl)obj;
                if (double.IsNaN(ctrl.getValue()) || double.IsNaN(ctrl.getValue2())) valid = false;
            }

            if (valid == true)
                createCmd.Enabled = true;
            else
                createCmd.Enabled = false;
        }

        [PreEmptive.Attributes.Feature("API.CreateCompany")]
        private void createCmd_Click(object sender, EventArgs e)
        {
            eCompany.eManager.eManager eM = new eManager.eManager();
            foreach (Control obj in accountTableLayoutPanel.Controls)
            {
                eCompany.Custom_Controls.small_account_ctrl ctrl = (eCompany.Custom_Controls.small_account_ctrl)obj;
                double val = ctrl.getValue();
                string cur = ctrl.Currency;

                if (val > 0)
                {
                    eObj.account acc = eM.getAccount(m_company, cur);
                    eObj.transaction t = new eObj.transaction();
                    t.Date = DateTime.Today;
                    t.id = Guid.NewGuid().ToString();
                    t.Type = eObj.transaction_type.Adjust;
                    t.Value = val;
                    acc.transaction_list.Add(t);
                }
            }

            foreach (Control obj in employeeTableLayoutPanel.Controls)
            {
                eCompany.Custom_Controls.small_employee_ctrl ctrl = (eCompany.Custom_Controls.small_employee_ctrl)obj;
                double val = ctrl.getValue();
                string emp_id = ctrl.EmployeeId;

                eObj.employee emp = eM.getEmployee(m_company, Guid.Parse(emp_id));
                if (emp != null)
                {
                    eObj.salary sal = new eObj.salary();
                    sal.date = DateTime.Now;
                    sal.value = val/8;
                    emp.salary_list.Add(sal);
                }
            }
            eObj.employee corp_emp = new eObj.employee();
            corp_emp.id = Guid.NewGuid().ToString();
            corp_emp.api_id = m_org.api_id;
            corp_emp.fireable = false;
            corp_emp.date_in = DateTime.Now;
            eObj.salary corp_sal = new eObj.salary();
            corp_sal.date = DateTime.Today;
            corp_sal.value = 0;
            corp_emp.salary_list.Add(corp_sal);
            m_company.employee_list.Add(corp_emp);

            foreach (Control obj in rawTableLayoutPanelExtended.Controls)
            {
                eCompany.Custom_Controls.small_raw_ctrl ctrl = (eCompany.Custom_Controls.small_raw_ctrl)obj;
                double val = ctrl.getValue();
                if (ctrl.isRaw == false)
                {
                    //company stock
                    eObj.stock s = new eObj.stock();
                    s.date = DateTime.Today;
                    s.production_cost = 0;
                    s.volume_in = val;
                    s.volume_out = 0;

                    m_company.company_stock.Clear();
                    m_company.company_stock.Add(s);
                }
                else
                {
                    //raw stock
                    eObj.material_stock ms = eM.getMaterialStock(m_company, ctrl.rawType);
                    if (ms != null)
                    {
                        eObj.material m = new eObj.material();
                        m.date = DateTime.Today;
                        m.id = Guid.NewGuid().ToString();
                        m.unit_price = 0;
                        m.volume_in = val;
                        m.volume_out = 0;

                        ms.materials.Clear();
                        ms.materials.Add(m);
                    }
                }
            }

            foreach (Control obj in shopsTableLayoutPanelExtended.Controls)
            {
                eCompany.Custom_Controls.small_shop_ctrl ctrl = (eCompany.Custom_Controls.small_shop_ctrl)obj;
                double val1 = ctrl.getValue();
                double val2 = ctrl.getValue2();

                eObj.shop s = eM.getShop(m_company, ctrl.Currency);
                if (s != null)
                {
                    eObj.shop_stock ss = new eObj.shop_stock();
                    ss.date = DateTime.Today;
                    ss.production_cost = 0;
                    ss.volume_in = val1;
                    ss.volume_out = 0;
                    ss.unit_price = val2;
                    s.stocks.Add(ss);
                }
            }

            m_org.company_list.Add(m_company);
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
            this.Close();
        }

        private void stopLoadCompany(eObj.company c)
        {
            eManager.eManager eM = new eManager.eManager();

            lblCompanyNameLink.Text = c.name;
            companyTypePictureBox.Image = Tools.GetCompanyTypeImage(c.type);
            if (!eRules.eCompanyRules.isMaterialCompanyType(c.type))
            {
                customPointsProgressBar.Value = c.customized_point;
                customPointLbl.Text = c.customized_point.ToString();
            }
            else
                company_detailPanel.Visible = false;

            accountTableLayoutPanel.Controls.Clear();
            foreach (eObj.account acc in c.account_list)
            {
                eCompany.Custom_Controls.small_account_ctrl ctrl = new Custom_Controls.small_account_ctrl(this.validateCustomControls, acc.currency, acc.name);
                ctrl.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
                accountTableLayoutPanel.Controls.Add(ctrl);
            }

            employeeTableLayoutPanel.Controls.Clear();
            foreach (eObj.employee emp in c.employee_list)
            {
                eCompany.Custom_Controls.small_employee_ctrl ctrl = new Custom_Controls.small_employee_ctrl(this.validateCustomControls, emp.id, emp.name);
                ctrl.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
                employeeTableLayoutPanel.Controls.Add(ctrl);
            }

            rawTableLayoutPanelExtended.Controls.Clear();
            eCompany.Custom_Controls.small_raw_ctrl ctrl_comp_stock = new Custom_Controls.small_raw_ctrl(this.validateCustomControls, c.type);
            ctrl_comp_stock.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
            ctrl_comp_stock.setValue(eM.getStockCount(c));
            rawTableLayoutPanelExtended.Controls.Add(ctrl_comp_stock);

            foreach (eObj.material_stock ms in c.material_list)
            {
                eCompany.Custom_Controls.small_raw_ctrl ctrl = new Custom_Controls.small_raw_ctrl(this.validateCustomControls, ms.material_type);
                ctrl.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
                ctrl.setValue(eM.getMaterialCount(c, ms.material_type));
                rawTableLayoutPanelExtended.Controls.Add(ctrl);
            }

            shopsTableLayoutPanelExtended.Controls.Clear();
            foreach (eObj.shop s in c.shops)
            {
                eCompany.Custom_Controls.small_shop_ctrl ctrl = new Custom_Controls.small_shop_ctrl(this.validateCustomControls, s.currency, "Shop " + s.currency);
                ctrl.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;

                double volume = eM.getShopStock(c, s.currency);
                double unit_price = 0;
                if (volume != 0)
                    unit_price = eM.getShopValue(s) / volume;
                ctrl.setValue(volume);
                ctrl.setValue2(unit_price);

                shopsTableLayoutPanelExtended.Controls.Add(ctrl);
            }
            m_company = c;

            this.Height = 543;
            loadCmd.Text = "Load from eRepublik";
            this.Cursor = Cursors.Default;
            loadCmd.Enabled = true;
            companyIdTxt.Enabled = true;
        }

        private void loadCompanyProc(object o)
        {
            string companyId = (string)o;
            eApi.api api = new eApi.api();
            try
            {
                eObj.company c = api.loadCompanyFromWeb(companyId, this.updateScreenThreadSafe);
                this.Invoke(this.stopLoadDelegate, new Object[] { c });
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error loading company : " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
